package com.kgc.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {

    private Connection connection;
    private PreparedStatement ps;
    private ResultSet rs;
    private static ComboPooledDataSource dataSource;

    static{ // 连接池每次只实例化一次
        // 1.初始化连接池
        dataSource = new ComboPooledDataSource();
    }

    /**
     * 打开数据库
     */
    protected void openConnection(){
        try {

            // 2.从连接池中获取连接对象
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 查询封装
     * @param sql
     * @param objs
     * @return
     */
    protected ResultSet getExecuteQuery(String sql ,Object... objs){
        try {
            // 1.获取连接
            this.openConnection();
            // 2.搬运工
            ps=connection.prepareStatement(sql);
            // 3.赋值占位
            for (int i = 0; i < objs.length; i++) {
                ps.setObject(i+1,objs[i]);
            }
            return ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


    /**
     * 增删改
     * @param sql
     * @param objs
     * @return
     */
    protected int getExecuteUpdate(String sql ,Object... objs){
        try {
            // 1.获取连接
            this.openConnection();
            // 2.搬运工
            ps=connection.prepareStatement(sql);
            // 3.赋值占位
            for (int i = 0; i < objs.length; i++) {
                ps.setObject(i+1,objs[i]);
            }
            return ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            this.closeConnection();
        }
        return 0;
    }


    /**
     * 关闭数据库
     */
    protected void closeConnection(){
        try {
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


}
